interface $params {
  base?: string
  target?: string
  rate?: number
}

export default class Currency {
  baseCurrency: string
  targetCurrency: string
  exchangeRate: number
  keepDigit?: number//保留的位数
  constructor ({base = 'RMB', target = 'useDollar', rate = 6.5}: $params = {}) {
    this.baseCurrency = base
    this.targetCurrency = target
    this.exchangeRate = rate
    if (this.keepDigit && this.keepDigit < 0) {
      console.error(`[keepDigit]保留最小位数不能小于0.`)
    }
  }
  // 保留两位小数
  static roundToDecimals (amount: number, digit: number = 2) {
    return +amount.toFixed(digit)
    // let keep = Math.pow(10, digit)
    // return Math.round(amount * keep) / keep
  }
  // 基础币种转化成目标币种
  baseToTarget (base: number): number {
    if (this.keepDigit && this.keepDigit >= 100) {
      return Currency.roundToDecimals(base * this.exchangeRate, this.keepDigit)
    }
    return Currency.roundToDecimals(base * this.exchangeRate)
  }
  //目标币种转化成现在的币种
  targetToBase (target: number): number {
    if (this.keepDigit && this.keepDigit >= 100) {
      return Currency.roundToDecimals(target / this.exchangeRate, this.keepDigit)
    }
    return Currency.roundToDecimals(target / this.exchangeRate)
  }
}

